package org.tio.sitexxx.all;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.im.server.Ims;
import org.tio.sitexxx.service.init.ZkInit;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.LoadData;
import org.tio.utils.json.Json;
import org.tio.utils.zk.Zk;

/**
 * @author tanyaowu 
 * 2016年11月24日 下午1:21:36
 */
public class ZkConnectionStateListener implements ConnectionStateListener {
	private static Logger log = LoggerFactory.getLogger(ZkConnectionStateListener.class);

	boolean	startIm		= true;	//P.getInt("start.im", 1) == 1;
	boolean	startView	= true;	//P.getInt("start.view", 1) == 1;

	public static final ZkConnectionStateListener me = new ZkConnectionStateListener();

	/** 
	 * @param client
	 * @param newState
	 * @author tanyaowu
	 */
	@Override
	public void stateChanged(CuratorFramework client, ConnectionState newState) {
		if (newState == ConnectionState.CONNECTED) {
			try {
				if (!Zk.exists(Const.ZkNode.ROOT)) {
					Zk.createOrUpdate(Const.ZkNode.ROOT, "", CreateMode.PERSISTENT);
				}

				if (!Zk.exists(Const.ZkNode.IM_SERVERS)) {
					Zk.createOrUpdate(Const.ZkNode.IM_SERVERS, "", CreateMode.PERSISTENT);
				}

			} catch (Exception e) {
				log.error(e.toString(), e);
			}

			//创建相关节点
			try {
				String myip = org.tio.sitexxx.service.vo.Const.SERVICE_HOST;
				if (startIm) {
					String mypath = Const.ZkNode.IM_SERVERS + "/" + myip;
					LoadData loadData = Ims.createLoadData();
					Zk.createOrUpdate(mypath, Json.toJson(loadData), CreateMode.EPHEMERAL);
				}

			} catch (Exception e) {
				log.error(e.toString(), e);
			}
		} else if (newState == ConnectionState.LOST) {//处理session过期
			try {
				log.error("zk session 超时了");
				ZkInit.init(ZkClientDecorator.me);
				//				Zk.zkclient.getConnectionStateListenable().addListener(ZkConnectionStateListener.me);
			} catch (Exception e) {
				log.error(e.toString(), e);
			}
		}
	}

}
